# coding=utf-8
# coding=utf-8

import tornado.web

import WrapCursor
from WorkManager import *
from database.models.TimingSwitch import TimingSwitch


class ModTimingSwitchNameHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        print(self.request.path)
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            CheckJsonKeys(ojson, 'id', 'name')
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except:
            self.write(r.Error('request data error'))
            return
        tid = ojson['id']
        name = ojson['name']
        if tid == "*":
            self.write(r.Error('you are attack server,warning'))
            return
        if name is None or name == '' or name == u'':
            self.write(r.Error(u'名字不能为空'))
            return
        s = Session()
        ts = s.query(TimingSwitch).filter_by(id=int(tid)).all()
        if ts is None or len(ts) != 1:
            self.write(r.Error(u'需要修改名字的定时模式id不存在'))
            return
        ts[0].desc = name
        try:
            s.commit()
        except Exception as e:
            logging.warn(e.message)
            self.write(r.Error(u'修改失败'))
            return
        self.write(r.Ok(u'成功'))
        return
